package com.eastfair.venueservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.echo.core.EchoService;
import com.eastfair.venueservice.dto.*;
import com.eastfair.venueservice.entity.ServiceOrder;
import com.eastfair.venueservice.service.ExhibitionSettlementService;
import com.eastfair.venueservice.service.ServiceOrderService;
import com.eastfair.venueservice.service.VenueManageServiceOrderService;
import com.eastfair.venueservice.vo.ServiceOrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 服务订单
 * </p>
 *
 * @author dq
 * @date 2022-09-28
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/serviceOrder")
@Api(value = "ServiceOrder", tags = "服务订单")
@PreAuth(replace = "common:serviceOrder:")
public class ServiceOrderController extends SuperController<ServiceOrderService, Long, ServiceOrder, ServiceOrderPageQuery, ServiceOrderSaveDTO, ServiceOrderUpdateDTO> {

    @Resource
    private EchoService echoService;

    @Resource
    private ServiceOrderService serviceOrderService;

    @Resource
    private VenueManageServiceOrderService venueManageServiceOrderService;

    @Resource
    private ExhibitionSettlementService exhibitionSettlementService;

    @Override
    public void handlerResult(IPage<ServiceOrder> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<ServiceOrder> serviceOrderList = list
                .stream()
                .map((map) -> ServiceOrder.builder().build())
                .collect(Collectors.toList());
        return R.success(baseService.saveBatch(serviceOrderList));
    }

    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ServiceOrderPageQuery> params) {
        ServiceOrderPageQuery pageQuery = params.getModel();
        //分页处理
        if (ContextUtil.getProjectId() != null) {
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 分页查询服务订单列表.
     *
     * @param pageParams the page params
     * @return the r
     */
    @ApiOperation("分页查询服务订单列表")
    @PostMapping("/query/serviceOrder")
    public R<Page<ServiceOrderVO>> queryServiceOrders(@RequestBody PageParams<ServiceOrderDTO> pageParams) {
        log.info("queryServiceOrders - 分页查询服务订单列表, pageParams={}", pageParams);
        try {
            return R.successDef(venueManageServiceOrderService.listServiceOrderVOs(pageParams));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 订单编号获取服务订单VO.
     *
     * @param orderNumber the order number
     * @return the by id
     */
    @ApiOperation("订单编号获取服务订单VO")
    @GetMapping("/get/{orderNumber}")
    public R<ServiceOrderVO> getById(@PathVariable("orderNumber") String orderNumber) {
        log.info("getById - 订单编号获取服务订单VO, orderNumber={}", orderNumber);
        try {
            return R.successDef(venueManageServiceOrderService.getVOByOrderNumber(orderNumber));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 保存订单.
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @ApiOperation("保存服务订单")
    @SysLog("添加服务订单")
    @PostMapping("/save")
    public R<ServiceOrder> saveServiceOrder(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("saveServiceOrder - 保存服务订单, serviceOrderDTO={}", serviceOrderDTO);
        try {
            return R.successDef(venueManageServiceOrderService.saveServiceOrderForVenue(serviceOrderDTO));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 修改服务订单.
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @ApiOperation("修改服务订单")
    @SysLog("修改服务订单")
    @PostMapping("/update")
    public R<ServiceOrder> updateServiceOrder(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("updateServiceOrder - 修改服务订单, serviceOrderDTO={}", serviceOrderDTO);
        try {
            return R.successDef(venueManageServiceOrderService.updateServiceOrder(serviceOrderDTO));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 提交订单.
     *
     * @param orderNumber the order number
     * @return the r
     */
    @ApiOperation("提交订单")
    @SysLog("提交服务订单")
    @GetMapping("/submit/{orderNumber}")
    public R<Boolean> submit(@PathVariable("orderNumber") String orderNumber) {
        log.info("submit - 提交订单, orderNumber={}", orderNumber);
        try {
            return R.successDef(venueManageServiceOrderService.submitServiceOrder(orderNumber));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 取消订单.
     *
     * @param orderNumber the order number
     * @return the r
     */
    @ApiOperation("取消订单")
    @SysLog("取消服务订单")
    @GetMapping("/cancel/{orderNumber}")
    public R<Boolean> cancel(@PathVariable("orderNumber") String orderNumber) {
        log.info("cancel - 取消订单, orderNumber={}", orderNumber);
        try {
            return R.successDef(venueManageServiceOrderService.cancelServiceOrder(orderNumber));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 支付订单.
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @SysLog("支付服务订单")
    @PostMapping("/pay")
    public R<Boolean> payServiceOrder(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("payServiceOrder - 支付订单, serviceOrderDTO={}", serviceOrderDTO);
        return R.successDef(venueManageServiceOrderService.payServiceOrder(serviceOrderDTO));
    }

    /**
     * 更新退款状态
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @PostMapping("/update/refundStatus")
    public R<Boolean> updateRefundStatus(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("refundServiceOrder - serviceOrderDTO={}", serviceOrderDTO);
        try {
            serviceOrderService.updateRefundStatus(serviceOrderDTO);
            return R.successDef(true);
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 更新开票状态
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @PostMapping("/update/invoiceStatus")
    public R<Boolean> updateInvoiceStatus(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("updateInvoiceStatus - 更新开票状态, serviceOrderDTO={}", serviceOrderDTO);
        try {
            serviceOrderService.updateInvoiceStatus(serviceOrderDTO);
            return R.successDef(true);
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 申请开票发站内信.
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @SysLog("申请开票发站内信")
    @PostMapping("/sendInnerMsg")
    public R<Boolean> sendInnerMsg(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("sendInnerMsg - 申请开票发站内信, serviceOrderDTO={}", serviceOrderDTO);
        return R.successDef(venueManageServiceOrderService.sendInnerMsg(serviceOrderDTO));
    }

    /**
     * 订单数据分析.
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @ApiOperation("订单数据分析")
    @PostMapping("/orderDataAnalysis")
    public R<Map<String,Object>> orderDataAnalysis(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("orderDataAnalysis - 订单数据分析, serviceOrderDTO={}", serviceOrderDTO);
        try {
            return R.successDef(baseService.orderDataAnalysis(serviceOrderDTO));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 订单数据分析-数量.
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @ApiOperation("订单数据分析-数量")
    @PostMapping("/orderNumTrend")
    public R<Map<String,Object>> orderNumTrend(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("orderDataAnalysis - 订单数据分析-数量, serviceOrderDTO={}", serviceOrderDTO);
        try {
            return R.successDef(baseService.orderNumTrend(serviceOrderDTO));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 订单数据分析-金额.
     *
     * @param serviceOrderDTO the service order dto
     * @return the r
     */
    @ApiOperation("订单数据分析-金额")
    @PostMapping("/orderAmountTrend")
    public R<Map<String,Object>> orderAmountTrend(@RequestBody ServiceOrderDTO serviceOrderDTO) {
        log.info("orderAmountTrend - 订单数据分析-金额, serviceOrderDTO={}", serviceOrderDTO);
        try {
            return R.successDef(baseService.orderAmountTrend(serviceOrderDTO));
        } catch (BizException e) {
            return R.fail(e);
        }
    }

    /**
     * 更新订单或结算单退款状态.
     *
     * @param BizStateDTO
     * @return the r
     */
    @PostMapping("/updateBizRefundState")
    public R<Boolean> updateBizRefundState(@RequestBody BizStateDTO BizStateDTO){
        return R.success(exhibitionSettlementService.updateBizRefundState(BizStateDTO));
    }

    /**
     * 更新订单或结算单开票状态.
     *
     * @param BizStateDTO
     * @return the r
     */
    @PostMapping("/updateBizInvoiceApplyState")
    public R<Boolean> updateBizInvoiceApplyState(@RequestBody BizStateDTO BizStateDTO){
        return R.success(exhibitionSettlementService.updateBizInvoiceApplyState(BizStateDTO));
    }

    /**
     * 导出订单.
     *
     * @param serviceOrderDTO the service order dto
     * @param response        the response
     * @throws Exception the exception
     */
    @PostMapping("/export")
    public void exportServiceOrder(@RequestBody ServiceOrderDTO serviceOrderDTO, HttpServletResponse response) throws Exception {
        log.info("exportServiceOrder - 导出订单, serviceOrderDTO={}", serviceOrderDTO);
        baseService.exportServiceOrder(serviceOrderDTO, response);
    }

    /**
     * 查询超时为支付订单.
     *
     * @param query the query
     * @return the r
     */
    @PostMapping("/query/timeout")
    public R<List<ServiceOrder>> queryTimeOutNotPay(@RequestBody ServiceOrderDTO query) {
        log.info("queryTimeOutNotPay - 查询超时为支付订单, query={}", query);
        return R.successDef(baseService.listTimeoutNotPayServiceOrder(query));
    }
}
